package com.klikmee.sms.core.base.resolvers;

import java.text.MessageFormat;

import org.apache.log4j.Logger;

import com.klikmee.sms.core.base.Core;
import com.klikmee.sms.core.base.dao.ServiceDAO;
import com.klikmee.sms.core.model.IncomingMessage;
import com.klikmee.sms.core.model.Service;

/**
 * Base class for resolvers that providers short code and message syntax
 * to resolve message to service.
 * @author makcro
 *
 */
public abstract class AbstractServiceResolver implements IncomingMessage2ServiceResolver {

	/**
	 * Logger instance
	 */
	private Logger logger = Logger.getLogger(AbstractServiceResolver.class);
	
	/**
	 * Ref to the core instance
	 */
	private Core core = null;
	
	/**
	 * <p>
	 * Initializes service resolver and loads all service definitions.
	 * </p>
	 */
	public void init() {
		// load all service definitions
		logger.info( "Abstract service resolver initialized." );
	}
	
	@Override
	public Service resolve(IncomingMessage incomingMessage) {
		// this is to be returned as result
		Service result = null;
		// get the mobile operator for this message
		
		// Iterate through all services and test for matching short code and sintax
		for (Service service : core.getServiceDefinitions()) {
			
			// check if destination address matches providers short code
			boolean shortCodeMatchesProvider = matchProviersShortCode(incomingMessage, service); 
			
			if(shortCodeMatchesProvider){
				// test if message text matches message text
				if(incomingMessage.getMessage().matches(service.getSintax())){
					result = service;
					logger.info(MessageFormat.format("Successfully matched incoming message to service [{0}]", result.getName()));
					break;
				}
			}
		}

		return result;
		
	}
	

	/**
	 * Matches incoming message destination address to the specific mobile operator's short code.
	 * @param incomingMessage incoming message who's destination is to be matched
	 * @param service TODO
	 * @return true if message's destination matches providers short code, otherwise false. 
	 */
	protected abstract boolean matchProviersShortCode(IncomingMessage incomingMessage, Service service); 
	
	public void setCore(Core core) {
		this.core = core;
	}
}
